package com.xiaojiu.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.xiaojiu.R;
import com.xiaojiu.bean.AdModel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Created by Jacky on 2016/10/31.
 * 广告轮播
 */
public class MyAdViewPager extends RelativeLayout {

    private ViewPager vPager;
    private List<AdModel> adModels;
    private LinearLayout vDotLayout;
    private ArrayList<ImageView> pointviews = new ArrayList<ImageView>();
    private Context mContext;
    private ADAdapter adAdapter;
    private OnPageOnclickListener pageOnclickListener;
    private int select = 0;
    private Subscription mSubscription;


    /**
     * 未选中指示器
     */
    private int indicator = R.drawable.indicator;

    /**
     * 选中指示器
     */
    private int indicator_focused = R.drawable.indicator_focused;

    /**
     * 是否滑动
     */
    private boolean slide = true;
    /**
     * 是否轮播
     */
    private boolean play = true;
    /**
     * 是否显示指示器
     */
    private boolean show_indicator = true;
    /**
     * 指示器的位置 0,左边，1中间，右边
     */

    private int location_indicator = 1;
    /**
     * 间隔时间
     * 毫秒单位
     */
    private int interval = 3000;
    /**
     * 是否按住的时候禁止自动滑动
     */
    private boolean isTouch = false;


    public MyAdViewPager(Context context) {
        super(context);
        this.mContext = context;
    }


    public MyAdViewPager(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyAdViewPager);
        indicator = typedArray.getInteger(R.styleable.MyAdViewPager_indicator_, indicator);
        indicator_focused = typedArray.getInteger(R.styleable.MyAdViewPager_indicator_focused_, indicator_focused);
        slide = typedArray.getBoolean(R.styleable.MyAdViewPager_slide_, slide);
        play = typedArray.getBoolean(R.styleable.MyAdViewPager_play_, play);
        show_indicator = typedArray.getBoolean(R.styleable.MyAdViewPager_show_indicator_, show_indicator);
        location_indicator = typedArray.getInteger(R.styleable.MyAdViewPager_location_indicator_, location_indicator);
        interval = typedArray.getInteger(R.styleable.MyAdViewPager_interval_, interval);
        typedArray.recycle();
    }

    public MyAdViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyAdViewPager);
        indicator = typedArray.getResourceId(R.styleable.MyAdViewPager_indicator_, indicator);
        indicator_focused = typedArray.getResourceId(R.styleable.MyAdViewPager_indicator_focused_, indicator_focused);
        slide = typedArray.getBoolean(R.styleable.MyAdViewPager_slide_, slide);
        play = typedArray.getBoolean(R.styleable.MyAdViewPager_play_, play);
        show_indicator = typedArray.getBoolean(R.styleable.MyAdViewPager_show_indicator_, show_indicator);
        location_indicator = typedArray.getInteger(R.styleable.MyAdViewPager_location_indicator_, location_indicator);
        interval = typedArray.getInteger(R.styleable.MyAdViewPager_interval_, interval);
        typedArray.recycle();
    }

    /**
     * 初始一些状态
     *
     * @param height
     */
    public void onInit(int height) {
        View view = LayoutInflater.from(mContext).inflate(
                R.layout.common_viewapger_item, null);
        addView(view);
        vDotLayout = (LinearLayout) view.findViewById(R.id.adddot);
        vPager = (ViewPager) view.findViewById(R.id.pager);
        FrameLayout.LayoutParams fl = new FrameLayout.LayoutParams(
                android.view.ViewGroup.LayoutParams.MATCH_PARENT, height);
        vPager.setLayoutParams(fl);
        if (location_indicator == 0) {
            vDotLayout.setGravity(Gravity.LEFT | Gravity.BOTTOM);
        } else if (location_indicator == 1) {
            vDotLayout.setGravity(Gravity.CENTER | Gravity.BOTTOM);
        } else if (location_indicator == 2) {
            vDotLayout.setGravity(Gravity.RIGHT | Gravity.BOTTOM);
        }
        if (!show_indicator) {
            vDotLayout.setVisibility(GONE);
        } else {
            vDotLayout.setVisibility(VISIBLE);
        }


        vPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                select = vPager.getCurrentItem();
                draw_Point(position % adModels.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        vPager.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {

                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        isTouch = true;
                        break;
                    case MotionEvent.ACTION_UP:
                        isTouch = false;
                        break;
                }
                return false;
            }
        });
    }

    /**
     * 初始指标点
     *
     * @param ads
     */
    private void initPoint(List<AdModel> ads) {
        ImageView imageView;
        for (int i = 0; i < ads.size(); i++) {
            imageView = new ImageView(mContext);
            imageView.setImageResource(indicator);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    new ViewGroup.LayoutParams(
                            android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
                            android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
            layoutParams.leftMargin = 10;
            layoutParams.rightMargin = 10;
            vDotLayout.addView(imageView, layoutParams);
            pointviews.add(imageView);
        }
    }

    private void draw_Point(int index) {
        for (int i = 0; i < pointviews.size(); i++) {
            pointviews.get(i).setImageResource(indicator);
        }
        pointviews.get(index).setImageResource(indicator_focused);
    }

    public void startLoop() {
        if (play) {
            if (mSubscription == null || mSubscription.isUnsubscribed()) {
                mSubscription = Observable.interval(interval, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread()).
                                subscribe(new Action1<Long>() {
                                    @Override
                                    public void call(Long aLong) {
                                        if (!isTouch) {
                                            select++;
                                            vPager.setCurrentItem(select);
                                        }
                                    }
                                });
            }


        }
    }

    public void stopLoop() {
        if (play) {
            if (mSubscription != null && !mSubscription.isUnsubscribed()) {
                mSubscription.unsubscribe();
            }
        }
    }

    /**
     * 设置轮播图片
     *
     * @param adModels
     */
    public void setData(List<AdModel> adModels) {
        if (adModels == null) {
            return;
        }
        this.adModels = adModels;
        pointviews.clear();
        vDotLayout.removeAllViews();
        select = 0;
        adAdapter = new ADAdapter(adModels);
        vPager.setAdapter(adAdapter);

        stopLoop();
        initPoint(adModels);
        draw_Point(0);
        if (adModels.size() > 1) {
            vPager.setCurrentItem((adModels.size()) * 100, false);
            select = 100 * adModels.size();
            startLoop();
        } else {
            vPager.setCurrentItem(0, false);
        }
    }

    public void setOnPageClickListener(OnPageOnclickListener pageOnclickListener) {
        this.pageOnclickListener = pageOnclickListener;
    }

    private class ADAdapter extends PagerAdapter {
        private List<AdModel> ads;

        public ADAdapter(List<AdModel> carAds) {
            this.ads = carAds;
        }

        @Override
        public int getCount() {
            return ads.size() > 1 ? Integer.MAX_VALUE : ads.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return (arg0 == arg1);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            final int index = position % ads.size();
            View view = LayoutInflater.from(mContext).inflate(
                    R.layout.viewpager_item_pic, null);
            final ImageView imageView = (ImageView) view.findViewById(R.id.pic);
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (pageOnclickListener != null) {
                        pageOnclickListener.onPage(index);
                    }
                }
            });
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    public interface OnPageOnclickListener {
        public void onPage(int index);
    }
}